package se.plingapp.backingbeans;

import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import se.plingapp.enterprisebeans.MessageFacade;
import se.plingapp.enterprisebeans.UserFacade;
import se.plingapp.entitybeans.Message;
import se.plingapp.entitybeans.User;

/**
 *
 * @author Jens Ljungblad
 */
@ManagedBean
@RequestScoped
public class ProfileBean {

    @EJB
    private UserFacade userFacade;

    private Long userId;

    private User user;

    @EJB
    private MessageFacade messageFacade;

    public Long getUserId() {
        return this.userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
        System.out.println("SETTING THE USER ID in object: " + this);
    }

    public User getUser() {
        if (this.user == null && this.userId != null) {
            this.user = userFacade.find(this.userId);
        }
        else if (this.userId == null && this.user == null) {
            return this.getActiveUser();
        }
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<Message> getMessages() {
        return messageFacade.findByUser(this.user);
    }

    public void follow() {
        String id = FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap().get("id");
        System.out.println("FOLLOWING ID:"+id);

        User activeUser = this.getActiveUser();
        User u = this.userFacade.find(Long.parseLong(id));
        activeUser.follow(u);
        userFacade.edit(activeUser);
    }

    public void unfollow() {
        String id = FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap().get("id");
        System.out.println("UNFOLLOWING ID:"+id);

        User activeUser = this.getActiveUser();
        User u = this.userFacade.find(Long.parseLong(id));
        activeUser.unfollow(u);
        userFacade.edit(activeUser);
    }

    public List<User> getFollowers() {
        return userFacade.findFollowersByUser(this.getUser());
    }

    private User getActiveUser() {
        FacesContext fc = FacesContext.getCurrentInstance();
        return (User) fc.getExternalContext().getSessionMap().get("user");
    }
}
